package com.harmontronics.hanma.paas.paas.token;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * @author ldb
 */
@Component("composeTokenKit")
public class ComposeTokenKit implements TokenKit {

    @Autowired
    private AppUserTokenKit appUserTokenKit;

    @Autowired
    private TenantUserTokenKit tenantUserTokenKit;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private MosTokenKit mosTokenKit;

    @Value("${mos.oss.enabled:false}")
    private Boolean mosEnabled;

    @Override
    public String getTokenHashKey(Long id) {
        if (mosEnabled != null && mosEnabled) {
            throw new UnsupportedOperationException();
        }
        String key = tenantUserTokenKit.getTokenKey();
        if (!StringUtils.isEmpty(key)) {
            return tenantUserTokenKit.getTokenHashKey(id);
        }
        return appUserTokenKit.getTokenHashKey(id);
    }

    @Override
    public StringRedisTemplate getRedisTemplate() {
        return stringRedisTemplate;
    }

    @Override
    public String getTokenKey() {
        if (mosEnabled != null && mosEnabled) {
            return mosTokenKit.getTokenKey();
        }
        String key = tenantUserTokenKit.getTokenKey();
        if (StringUtils.isEmpty(key)) {
            return appUserTokenKit.getTokenKey();
        }
        return key;
    }

    @Override
    public Long getId() {
        if (mosEnabled != null && mosEnabled) {
            return mosTokenKit.getId();
        }
        return parseId(this.getTokenKey());
    }

    @Override
    public Boolean getPreview() {
        throw new UnsupportedOperationException();
    }
}
